package com.ws.game.lesson1.keycontrol
{
	import com.ws.game.common.global.Global;
	import com.ws.game.common.errors.NullError;
	import com.ws.game.common.framework.BaseCtrl;
	import com.ws.game.common.framework.BaseGameObject;
	import com.ws.game.common.utils.MoveDirectionType;
	
	import flash.events.KeyboardEvent;
	import flash.ui.Keyboard;
	
	public class KeyBoardCtrl extends BaseCtrl
	{
		public function KeyBoardCtrl()
		{
			super();				
			setUpListener();
		}
		
		private function setUpListener():void{			
			Global.stage.addEventListener(KeyboardEvent.KEY_DOWN,onKeyDown);
			Global.stage.addEventListener(KeyboardEvent.KEY_UP,onKeyUp);
		}
		
		private function onKeyDown(event:KeyboardEvent):void{
			var me:ActionObject = _target as ActionObject;
			switch(event.keyCode)
			{
				case Keyboard.UP:
					me.direction = MoveDirectionType.UP;
					break;
				case Keyboard.DOWN:
					me.direction = MoveDirectionType.DOWN;
					break;
				case Keyboard.LEFT:
					me.direction = MoveDirectionType.LEFT;
					break;
				case Keyboard.RIGHT:
					me.direction = MoveDirectionType.RIGHT;
					break;
				default:break;
			}
		}
		
		private function onKeyUp(event:KeyboardEvent):void{
			var me:ActionObject = _target as ActionObject;
			var active:Array = new Array(Keyboard.UP,Keyboard.DOWN,Keyboard.LEFT,Keyboard.RIGHT);
			if (active.indexOf(event.keyCode) != -1) 
				me.direction = MoveDirectionType.STOP;
		}
		
		override public function dispose():void{
			this._target = null;
			Global.stage.removeEventListener(KeyboardEvent.KEY_DOWN,onKeyDown);
			Global.stage.removeEventListener(KeyboardEvent.KEY_UP,onKeyUp);			
		}
	}
}